import Editor from 'for-editor'
import { useState, createRef, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Button, Form, Input, Select, message } from 'antd';
import { upload } from '../api/file';
import { getAllcates } from '../api/cate'
import { addArticle, getArticleById, editArticle } from '../api/article'
const ArticleWrite = () => {
    // 文章内容
    const [form] = Form.useForm();
    const [value, setValue] = useState(null)
    const [title, setTitle] = useState(null)
    const [articleCateId, setArticleCateId] = useState(null)
    const { id } = useParams();
    const [cateList, setcateList] = useState([])
    useEffect(() => {
        getAllcates().then(res => {
            const list = res.data.map(v => {
                return {
                    value: v.id,
                    label: v.cateName
                }
            })
            console.log(list);
            setcateList(list)

        })
        if (id) {
            getArticleById(id).then(res => {
                console.log(res);
                if (res.data) {
                    setValue(res.data.content)
                    setTitle(res.data.title)
                    setArticleCateId(res.data.articleCateId)
                    console.log(title, 'title111');
                    console.log(value, 'content111');
                }
            })
        }
    }, [])



    const [messageApi, contextHolder] = message.useMessage();

    const navigate = useNavigate()
    // 编辑器配置，可以根据自己需要决定是否显示
    const toolbar = {
        h1: true, // h1
        h2: true, // h2
        h3: true, // h3
        h4: true, // h4
        img: true, // 图片
        link: true, // 链接
        code: true, // 代码块
        preview: true, // 预览
        expand: true, // 全屏
        /* v0.0.9 */
        undo: true, // 撤销
        redo: true, // 重做
        // save: true, // 保存
        /* v0.2.3 */
        subfield: true, // 单双栏模式
    }

    const $vm = createRef()
    const handleChange = (val) => {
        setValue(val)
        console.log(val);
    }
    const handleSave = (val) => {

        sessionStorage.setItem('content', val)
        navigate('/articleDetail')
    }
    // 图片转base64
    function fileToBase64Async(file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = (e) => {
                resolve(e.target.result);
            };
        });
    }

    const handleImg = async ($file) => {
        console.log($file);
        let file = new FormData();
        file.append('file', $file);
        const res = await upload(file)

        /*  const url = await fileToBase64Async($file) */
        $vm.current.$img2Url($file.name, res.data.picUrl)
        console.log(res.data.picUrl);
    }
    const onChange = (value) => {
        console.log(`selected ${value}`);
        setArticleCateId(value)
    };
    const submitArticle = () => {
        const { resetFields } = form;
        if (id) {
            const obj = {
                title,
                articleCateId,
                content: value,
                id
            }
            editArticle(obj).then(res => {
                if (res.status == 200) {
                    messageApi.open({
                        type: 'success',
                        content: '编辑成功！',
                        duration: 3,
                    });
                    form.resetFields();
                    setTitle("")
                    setValue("")
                    setArticleCateId(null)
                    setTimeout(() => {
                        navigate('/article')
                    }, 500)
                } else {
                    messageApi.open({
                        type: 'warning',
                        content: res.message,
                        duration: 3,
                    });
                }
            })
        } else {
            const obj = {
                title,
                articleCateId,
                content: value,
                userId: Number(sessionStorage.getItem('blogUserId'))
            }
            addArticle(obj).then(res => {
                if (res.status == 200) {
                    messageApi.open({
                        type: 'success',
                        content: '添加成功！',
                        duration: 3,
                    });

                    form.resetFields();
                    setTitle("")
                    setValue("")
                    setArticleCateId(null)
                } else {
                    messageApi.open({
                        type: 'warning',
                        content: res.message,
                        duration: 3,
                    });
                }
            })
        }
    }

    return (
        <div>{contextHolder}
            {
                <Form name="wrap"
                    form={form}
                    labelCol={{ flex: '110px' }}
                    labelAlign="left"
                    labelWrap
                    wrapperCol={{ flex: 1 }}
                    colon={false}
                >
                    <Form.Item label="文章标题" name="title" rules={[{ required: true }]}>
                        <div>
                            <span style={{ display: 'none' }}>   {title}</span>
                            <Input style={{ maxWidth: 600 }} value={title} onChange={(e) => { setTitle(e.target.value) }} />
                        </div>
                    </Form.Item>

                    <Form.Item label="文章分类" name="articleCateId" rules={[{ required: true }]}>
                        <div>
                            <span style={{ display: 'none' }}>   {articleCateId}</span>
                            <Select
                                style={{ maxWidth: 600 }}
                                showSearch
                                placeholder="请选择分类"
                                optionFilterProp="children"
                                value={articleCateId}
                                onChange={onChange}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                                options={cateList}
                            />
                        </div>
                    </Form.Item>
                    <Form.Item label="内容">
                        <div className='editor-box has-nav'>
                            <div className='main'>
                                <Editor ref={$vm} className="editor" toolbar={toolbar} onSave={handleSave} value={value} onChange={handleChange} preview={true} subfield={true} addImg={handleImg} />
                            </div>
                        </div >
                    </Form.Item>
                    <Form.Item label=" ">
                        <Button type="primary" htmlType="submit" onClick={submitArticle}>
                            完成
                        </Button>
                    </Form.Item>
                </Form>
            }

        </div>
    )
}
export default ArticleWrite

